/**
 * 
 */
package com.xb.cloud.common.model.tree;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.xb.cloud.common.constant.DbConstants;

/**
 * @author kexue
 *
 */
public class TreeUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(TreeUtils.class);

	static {

	}

	/*
	 * 将列表结构转换为=>树形数据结构
	 */
	public static <T> TreeNode<T> buildTree(List<TreeNode<T>> list) {
		TreeNode<T> rootNode = new TreeNode<T>();
		rootNode.setId(0L);
		rootNode.setName("虚拟根节点");
		rootNode.setParentId(null);

		if (list == null || list.size() == 0) {
			LOGGER.warn("列表为空，返回空");
			return null;
		}
		buildTreeInner(rootNode, list);
		return rootNode;
	}

	/**
	 * @param list
	 * @param level1
	 */
	private static <T> void buildTreeInner(TreeNode<T> currentRootNode, List<TreeNode<T>> list) {
		List<TreeNode<T>> children = buildChildrenByParentId(list, currentRootNode);
		if (children.size() > 0) {
			currentRootNode.setChildren(children);
		}

		for (TreeNode<T> child : children) {
			if (child.getIsLeaf() == DbConstants.FALSE) {
				// 非叶子节点
				buildTreeInner(child, list);
			}
		}
	}

	/**
	 * @param list
	 * @param level
	 * @return
	 */
	private static <T> List<TreeNode<T>> buildChildrenByParentId(List<TreeNode<T>> list, TreeNode<T> currentRootNode) {
		List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();
		for (TreeNode<T> node : list) {
			if (currentRootNode.getId().equals(node.getParentId())) {
				children.add(node);
			}
		}
		return children;
	}

	public static void main(String args[]) {

		TreeNode<String> e = new TreeNode<String>(1L, 0L, "节点1", "", DbConstants.FALSE, null, 1, "");
		String jsonString = JSON.toJSONString(e);
		LOGGER.info(jsonString);

		TreeNode parseObject = JSON.parseObject(jsonString, TreeNode.class);
		LOGGER.info(parseObject + "");

		List<TreeNode<String>> list = new ArrayList<TreeNode<String>>();

		TreeNode<String> e2 = new TreeNode<String>(2L, 1L, "节点2", "", DbConstants.FALSE, null, 1, "");
		TreeNode<String> e3 = new TreeNode<String>(3L, 1L, "节点3", "", DbConstants.FALSE, null, 1, "");
		TreeNode<String> e4 = new TreeNode<String>(4L, 2L, "节点4", "", DbConstants.TRUE, null, 1, "");
		TreeNode<String> e5 = new TreeNode<String>(5L, 2L, "节点5", "", DbConstants.TRUE, null, 1, "");
		TreeNode<String> e6 = new TreeNode<String>(6L, 2L, "节点6", "", DbConstants.TRUE, null, 1, "");
		TreeNode<String> e7 = new TreeNode<String>(7L, 3L, "节点7", "", DbConstants.FALSE, null, 1, "");
		TreeNode<String> e8 = new TreeNode<String>(8L, 7L, "节点8", "", DbConstants.TRUE, null, 1, "");
		list.add(e);
		list.add(e2);
		list.add(e3);
		list.add(e4);
		list.add(e5);
		list.add(e6);
		list.add(e7);
		list.add(e8);

		TreeNode<String> buildTree = buildTree(list);
		LOGGER.info(buildTree.toString());

	}
}
